package com.tiger.avatar 
{
	import com.greensock.easing.Linear;
	import com.greensock.TweenLite;
	import com.tiger.anim.BmdMovieClip;
	import com.tiger.utils.AvatarUtils;
	import flash.display.Sprite;
	import flash.geom.Point;
	
	/**
	 * ...
	 * @author wmTiger
	 */
	public class RoleAvatar extends Sprite implements IRoleAvatar
	{
		protected var mBmdMc:BmdMovieClip;
		protected var mInfo:RoleInfo;
		protected var mDir:int = 0;// 方向，按小键盘排列
		
		public function RoleAvatar(bmdmc:BmdMovieClip) 
		{
			mBmdMc = bmdmc;
			addChild(mBmdMc);
			mInfo = new RoleInfo();
			mInfo.speed = 30;
			
			mDir = 2;
		}
		
		public function movePath(paths:Array, handler:Function = null):void
		{
			var p:Point = paths.shift() as Point;
			var t:Number = getMoveTime(p.x, p.y);
			mDir = getDir(p.x, p.y);
			playDir();
			TweenLite.to(this, t, {x:p.x, y:p.y, ease:Linear.easeNone, onComplete:function ():void 
			{
				if (paths.length > 0) 
				{
					movePath(paths, handler);
				}
				else
				{
					if (handler != null) 
					{
						handler();
					}
					else
					{
						idle();
					}
				}
			} } );
		}
		
		private function playDir():void 
		{
			var dir:String = "";
			var dirEnd:String = "";
			switch (mDir) 
			{
				case 2:
					dir = AvatarConst.WALKING_DOWN;
					dirEnd = AvatarConst.WALKING_DOWN_END;
					//this.scaleX = 1;
				break;
				case 4:
					dir = AvatarConst.WALKING_LEFT;
					dirEnd = AvatarConst.WALKING_LEFT_END;
					//this.scaleX = -1;
				break;
				case 6:
					dir = AvatarConst.WALKING;
					dirEnd = AvatarConst.WALKING_END;
					//this.scaleX = 1;
				break;
				case 8:
					dir = AvatarConst.WALKING_UP;
					dirEnd = AvatarConst.WALKING_UP_END;
					//this.scaleX = 1;
				break;
				default:
			}
			mBmdMc.loopBetween2Frame(dir, dirEnd);
		}
		private function getDir(ex:Number, ey:Number):int
		{
			return AvatarUtils.get4Dir(new Point(this.x, this.y), new Point(ex, ey));
		}
		private function idle():void
		{
			mBmdMc.gotoAndStop(AvatarConst.IDLE);
		}
		private function getMoveTime(ex:Number, ey:Number):Number
		{
			return Math.sqrt((this.x - ex) * (this.x - ex) + (this.y - ey) * (this.y - ey)) / mInfo.speed;
		}
		
		public function teleport():void
		{
			mBmdMc.playOnceBetween2Frame(AvatarConst.TELEPORT, AvatarConst.TELEPORT_END);
		}
		
		/* INTERFACE com.tiger.avatar.IRoleAvatar */
		
		public function move(ex:int, ey:int):void 
		{
			var t:Number = getMoveTime(ex, ey);
			TweenLite.to(this, t, {x:ex, y:ey, ease:Linear.easeNone, onComplete:moveComplete } );
			mBmdMc.loopBetween2Frame(AvatarConst.WALKING, AvatarConst.WALKING_END);
		}
		
		private function moveComplete():void 
		{
			idle();
		}
		
		public function run(ex:int, ey:int):void 
		{
			
		}
		
		public function stand():void 
		{
			idle();
		}
		
	}

}